<template>
  <el-card style="width: 50%; margin: 10px">
    <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="100px">
      <el-form-item label="原密码" prop="password">
        <el-input v-model="data.form.password" show-password placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="data.form.newPassword" show-password placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="data.form.confirmPassword" show-password placeholder="请输入确认新密码"/>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button type="primary" @click="update">修改密码</el-button>
    </div>
  </el-card>
</template>

<script setup>
import {reactive,ref} from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次输入新密码'))
  } else if (value !== data.form.newPassword) {
    callback(new Error('两次输入新密码不一致!'))
  } else {
    callback()
  }
}

const formRef=ref()

const data = reactive({
  employee:JSON.parse(localStorage.getItem("xm-pro-employee")),
  form:{},
  rules:{
    password:[
        {required:true,message:'请输入密码',trigger:'blur'}
    ],
    newPassword:[
        {required:true,message:'请输入新密码',trigger:'blur'}
    ],
    confirmPassword:[
        {validator: validatePass, trigger: 'blur'}
    ]
  }
})
const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      checkPassword()
    } else {
      ElMessage.error("请检查输入")
      return false
    }
  })
}

const checkPassword = () => {
  request.get("/employee/getPassword",{
    params:{
      id: data.employee.id,
      password: data.form.password
    }
  }).then(res=>{
    if(res.data===0){
      data.employee.password = data.form.newPassword
      request.put("/employee/updatePassword",data.employee).then(res=>{
        if(res.code === '0'){
          ElMessage.success("修改成功")
          localStorage.setItem("xm-pro-employee", JSON.stringify(data.employee))
          setTimeout(()=>{
            location.href = "/Backend"
          },500)
        }else{
          ElMessage.error(res.msg)
        }
      })
    }else{
      ElMessage.error("原密码错误")
    }
  })
}
</script>

<style scoped>

</style>